<template>
  <child-page>
    <div class="components-form-demo-advanced-search">
      <a-form
        class="ant-advanced-search-form"
        :form="form"
        @submit="handleSubmit"
      >
        <a-form-item v-bind="formItemLayout" label="标题">
          <a-input
            v-decorator="[
              'title',
              {
                rules: [
                  { required: true, message: '请输入标题！' },
                  {
                    validator: $validate.validateLength,
                    max: 50,
                    min: 1
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="发帖人">
          <a-select
            v-decorator="[
              'set_posts_id',
              {
                rules: [{ required: true, message: '请选择！' }]
              }
            ]"
            placeholder="请选择！"
          >
            <a-select-option
              v-for="(item, index) in posterList"
              :key="index"
              :value="item.id"
            >
              {{ item.username }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="发帖类别">
          <a-radio-group
            @change="changeType"
            v-decorator="[
              'checkboxgroup',
              {
                rules: [
                  { required: true, message: '必填项' },
                  {
                    validator: $validate.validateLength,
                    max: 50,
                    min: 1
                  }
                ]
              }
            ]"
          >
            <a-radio value="1">
              群组
            </a-radio>
            <a-radio value="2">
              影视学堂
            </a-radio>
            <a-radio value="3">
              项目
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="群组" v-if="showGroup">
          <a-select
            v-decorator="[
              'group_id',
              {
                rules: [{ required: true, message: '请选择！' }]
              }
            ]"
            placeholder="请选择！"
          >
            <a-select-option
              v-for="(item, index) in groupInfo"
              :key="index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-bind="formItemLayout"
          label="影视学堂ID"
          v-if="showVideo"
        >
          <a-input v-decorator="['movie_id', { rules: rule.userName }]" />
        </a-form-item>
        <a-form-item
          v-bind="formItemLayout"
          label="项目名称"
          v-if="showProject"
        >
          <a-select
            v-decorator="[
              'item_id',
              {
                rules: [{ required: true, message: '请选择！' }]
              }
            ]"
            placeholder="请选择！"
          >
            <a-select-option
              v-for="(item, index) in projectSelect"
              :key="index"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="内容" v-bind="formItemLayout" required>
          <quill-editor
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
          >
          </quill-editor>
        </a-form-item>
        <a-form-item label="上传图片" v-bind="formItemLayout">
          <div class="clearfix">
            <a-upload
              v-decorator="[
                'img',
                {
                  initialValue: initInfo.uploadM,
                  valuePropName: 'fileList',
                  getValueFromEvent: normFileB,
                  rules: [{ required: true, message: '请上传轮播图' }]
                }
              ]"
              accept="image/*"
              :customRequest="upload"
              listType="picture-card"
              name="file"
              :multiple="true"
              :action="$api.upload"
              :data="postData"
              :beforeUpload="beforeUploadB"
              :showUploadList="format()"
              @change="bannerChange"
            >
              <div v-if="fileList.length < 9">
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传轮播图</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'center' }">
            <a-button type="primary" html-type="submit">
              提交
            </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </child-page>
</template>

<script>
import childPage from "@/components/childPageContent/index";
import validate from "@/tool/validateFunction";
import { getToken } from "@/tool/qiniu";
import reqwest from "reqwest";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "add",
  components: {
    childPage,
    quillEditor
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      athList: [],
      statusOption: [{ label: "在用", value: 1 }, { label: "停用", value: 2 }],
      sexOption: [{ label: "男", value: 1 }, { label: "女", value: 2 }],
      rule: {
        nickName: [
          { required: true, message: "必填项" },
          { validator: validate.validateLength, max: 15, min: 1 }
        ],
        password: [{ required: true, message: "必填项" }],
        checkPsw: [{ required: true, message: "必填项" }],
        userName: [{ required: true, message: "必填项" }],
        email: [{ validator: validate.validateEmail }],
        phone: [{ validator: validate.validatePhoneNumber }],
        role: [{ required: true, message: "必填项" }]
      },
      initInfo: {
        status: 1
      },
      postData: {
        token: ""
      },
      showVideo: false,
      showGroup: false,
      showProject: false,
      previewVisible: false,
      previewImage: "",
      fileList: [],
      loading: false,
      content: "",
      editorOption: {
        theme: "snow",
        modules: {
          toolbar: [
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], //字体
            [{ align: [] }] //对齐方式
          ]
        }
      },
      groupInfo: [],
      projectSelect: [],
      posterList: [],
      userInfo: ""
    };
  },
  methods: {
    format() {
      return { showPreviewIcon: false, showRemoveIcon: true };
    },
    changeType(checkedValues) {
      checkedValues.target.value.indexOf("1") === -1
        ? (this.showGroup = false)
        : (this.showGroup = true);
      checkedValues.target.value.indexOf("2") === -1
        ? (this.showVideo = false)
        : (this.showVideo = true);
      checkedValues.target.value.indexOf("3") === -1
        ? (this.showProject = false)
        : (this.showProject = true);
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {
        if (!error) {
          if (this.content === "") {
            this.$notification.warning({
              message: "请填写内容！"
            });
          } else {
            if (values.img.length > 9) {
              this.$notification.warning({
                message: "最多只能上传9张图片！"
              });
            } else {
              let obj = values;
              if (values.img) {
                let img = [];
                values.img.forEach(item => {
                  img.push(item.originFileObj.response.key);
                });
                img = img.join(",");
                obj.img = img;
              }
              obj.describe = this.content;
              delete obj.checkboxgroup;
              for (let item of this.posterList) {
                if (item.id === obj.set_posts_id) {
                  obj.set_posts_name = item.username;
                }
              }
              this.$ajax
                .post(this.$api.addPosts, obj)
                .then(() => {
                  this.$notification.success({
                    message: "操作成功"
                  });
                  this.$router.push({ name: "associationPosted" });
                })
                .catch(err => {
                  this.$notification.error({
                    message: err
                  });
                });
            }
          }
        } else {
          return false;
        }
      });
    },
    normFileB(e) {
      return e && e.fileList;
    },
    beforeUploadB(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "Posted/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
    },
    upload(data) {
      let formData = new FormData();
      formData.append("file", data.file);
      let timestamp2 = new Date().getTime();
      let typeArr = data.file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "Posted/" + timestamp2 + "." + type;
      let token = getToken(savekey);
      formData.append("token", token);
      this.saveFile(formData, data);
    },
    saveFile(formData, data) {
      data.onProgress();
      reqwest({
        url: this.$api.upload,
        method: "post",
        processData: false,
        data: formData,
        success: e => {
          data.file.response = e;
          data.onSuccess();
        },
        error: () => {
          data.OnError();
        }
      });
    },
    onEditorBlur() {}, // 失去焦点事件
    handleReset() {
      this.form.resetFields();
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    bannerChange({ fileList }) {
      this.fileList = fileList;
    },
    getInfo() {
      this.$ajax
        .get(this.$api.addPosts, false)
        .then(res => {
          this.groupInfo = res.groupInfo;
          this.projectSelect = res.project;
          this.posterList = res.adminInfo;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    this.getInfo();
  }
};
</script>

<style scoped lang="less"></style>
